package com.example.lenovo.sbns.Activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVOSCloud;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.SaveCallback;
import com.example.lenovo.sbns.R;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by 49670 on 2016/6/10.
 */
public class selfTalk extends Activity {

    private Button button1;
    private EditText editText1,editText2;
    private ImageButton imageButton;
    private ImageView imageView;
    private TextView Error;
    private String PhotoPath;
    private String name = "小明";
    private int img = R.mipmap.touxiang1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.selftalk);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.selftalk_title);

        editText1 = (EditText) findViewById(R.id.self_title);
        editText2 = (EditText) findViewById(R.id.self_content);
        imageButton = (ImageButton) findViewById(R.id.self_photo);
        imageView = (ImageView) findViewById(R.id.self_img);
        Error = (TextView) findViewById(R.id.self_ErrorPrint);

        /*拍照监听*/
        imageButton.setOnClickListener(
                new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // 跳转至拍照界面
                        Intent intentPhote = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        intentPhote.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                        File out = new File(getPhotopath());
                        Uri uri = Uri.fromFile(out);
                        // 获取拍照后未压缩的原图片，并保存在uri路径中
                        intentPhote.putExtra(MediaStore.EXTRA_OUTPUT, uri);
//                intentPhote.putExtra(MediaStore.Images.Media.ORIENTATION, 180);
                        startActivityForResult(intentPhote, 2000);
                    }
                }
        );


        button1 = (Button) findViewById(R.id.self_putbt);
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(CheckTalk())
                    CommitTalk();
            }
        });
    }

    /**
     * 添加成功对话框
     */
    private void dialog1(){
        AlertDialog.Builder builder=new AlertDialog.Builder(selfTalk.this);
        builder.setTitle("操作信息");
        builder.setMessage("发表成功！");
        builder.setIcon(R.mipmap.ic_launcher);
        builder.setPositiveButton("返回", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss(); //关闭dialog
            }
        });
        builder.create().show();
    }

    /**
     * 检查说说
     * */
    private boolean CheckTalk(){
        if(editText2.getText().toString().length()==0){
            Error.setText("内容不全！");
            return false;
        }
        if(editText1.getText().toString().length()==0){
            Error.setText("标题不全！");
            return false;
        }
        return  true;
    }

    /**
     * 提交个人说说
     * */
    private void CommitTalk(){
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日 ");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String str = formatter.format(curDate);
        /*连接数据库*/
        AVOSCloud.initialize(this, "Po6OudEc9QxRgv1qcussxBxi-gzGzoHsz", "EFNsW7y5aXtKMkpU50xyhHNk");
        AVObject testObject = new AVObject("Talk");
        testObject.put("talktitle",editText1.getText());
        testObject.put("talkcontent",editText2.getText());
        testObject.put("prority",1);
        testObject.put("talktime",str);
        testObject.put("talkname",name);
        testObject.put("talkimage",img);
        testObject.put("talkpicture",PhotoPath);
        testObject.saveInBackground(new SaveCallback() {
            @Override
            public void done(AVException e) {
                if (e == null) {
                    Log.d("saved", "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^success!");
                }
            }
        });

        Intent intent = new Intent(selfTalk.this, Index.class);
        startActivity(intent);
    }

    /**
     * 获取原图片存储路径
     * @return
     */
    private String getPhotopath() {
        // 照片全路径
        String fileName = "";
        // 文件夹路径
        String pathUrl = Environment.getExternalStorageDirectory()+"/mymy/";
        String imageName = "imageTest.jpg";
        File file = new File(pathUrl);
        file.mkdirs();// 创建文件夹
        fileName = pathUrl + imageName;
        PhotoPath = fileName;
        return fileName;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 2000 && resultCode == Activity.RESULT_OK) {
            Bitmap bitmap = getBitmapFromUrl(getPhotopath(), 313.5, 462.0);
            saveScalePhoto(bitmap);
            imageView.setImageBitmap(bitmap);
        }
    }
    /**
     * 根据路径获取图片资源（已缩放）
     * @param url 图片存储路径
     * @param width 缩放的宽度
     * @param height 缩放的高度
     * @return
     */
    private Bitmap getBitmapFromUrl(String url, double width, double height) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true; // 设置了此属性一定要记得将值设置为false
        Bitmap bitmap = BitmapFactory.decodeFile(url);
        // 防止OOM发生
        options.inJustDecodeBounds = false;
        int mWidth = bitmap.getWidth();
        int mHeight = bitmap.getHeight();
        Matrix matrix = new Matrix();
        float scaleWidth = 1;
        float scaleHeight = 1;
        // 按照固定宽高进行缩放
        // 这里希望知道照片是横屏拍摄还是竖屏拍摄
        // 因为两种方式宽高不同，缩放效果就会不同
        // 这里用了比较笨的方式
        if(mWidth <= mHeight) {
            scaleWidth = (float) (width/mWidth);
            scaleHeight = (float) (height/mHeight);
        } else {
            scaleWidth = (float) (height/mWidth);
            scaleHeight = (float) (width/mHeight);
        }
//        matrix.postRotate(90); /* 翻转90度 */
        // 按照固定大小对图片进行缩放
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap newBitmap = Bitmap.createBitmap(bitmap, 0, 0, mWidth, mHeight, matrix, true);
        // 用完了记得回收
        bitmap.recycle();
        return newBitmap;
    }

    /**
     * 存储缩放的图片
     *  图片数据 data
     */
    private void saveScalePhoto(Bitmap bitmap) {
        // 照片全路径
        String fileName = "";
        // 文件夹路径
        String pathUrl = Environment.getExternalStorageDirectory().getPath()+"/mymy/";
        String imageName = "imageScale.jpg";
        FileOutputStream fos = null;
        File file = new File(pathUrl);
        file.mkdirs();// 创建文件夹
        fileName = pathUrl + imageName;
        try {
            fos = new FileOutputStream(fileName);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos);
            final AVFile upload = AVFile.withAbsoluteLocalPath("Product.jpg", fileName);
            upload.saveInBackground(new SaveCallback() {
                @Override
                public void done(AVException e) {
                    PhotoPath = upload.getUrl();
                }
            });

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                fos.flush();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
